﻿using KPIS.DBM;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;
using KPIS.GERP.GFMS.APP.App_UI.Commons;
using KPIS.GERP.GFMS.DAL;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.MODEL;
using System;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using SystemInfo = KPIS.GERP.GFMS.MODEL.SystemInfo;

namespace KPIS.GERP.GFMS.APP.App_UI.Forms
{
    public partial class FIM_MoneyRequests_Old : System.Web.UI.Page
    {
        Main main = new Main();
        IBLL_FIM_MoneyRequests mr = new B_FIM_MoneyRequests();
        IBLL_FIM_MoneyRequestDtls mrd = new B_FIM_MoneyRequestDtls();
        IBLL_FIM_MoneyRequestTravelers mrTrav = new B_FIM_MoneyRequestTravelers();
        IBLL_FIM_MoneyRequestDtlsRates mrRate = new B_FIM_MoneyRequestDtlsRates();
        IBLL_FIM_MAS_BorrowTypes bt = new B_FIM_MAS_BorrowTypes();
        IBLL_BGM_MAS_Source source = new B_BGM_MAS_Source();
        IBLL_HRM_MP_WorkAreas area = new B_HRM_MP_WorkAreas();
        B_MessageSend send = new B_MessageSend();
        IBLL_FIM_MAS_Events ev = new B_FIM_MAS_Events();
        IBLL_BGM_MAS_ExpenseGroup expgrp = new B_BGM_MAS_ExpenseGroup();
        IBLL_BGM_ProjectOperation oper = new B_BGM_ProjectOperation();
        IBLL_BGM_ProjectOperationReport operRpt = new B_BGM_ProjectOperationReport();
        IBLL_FIM_SystemControls sc = new B_FIM_SystemControls();
        IBLL_HRM_PR_PayrollDtls prd = new B_HRM_PR_PayrollDtls();
        IBLL_FIM_MAS_ExpenseRates rate = new B_FIM_MAS_ExpenseRates();
        B_ICM_MAS_ResourceItem icmItem = new B_ICM_MAS_ResourceItem();
        IBLL_BGM_ProjectOperation ProjOper = new B_BGM_ProjectOperation();
        IBLL_BGM_ProjectOperationExpense ProjOperExpen = new B_BGM_ProjectOperationExpense();
        IBLL_HRM_PS_Employees emplist = new B_HRM_PS_Employees();
        IBLL_FIM_Payments pay = new B_FIM_Payments();
        DBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //======= test only =========
                //Session["EmpSeq"] = "1";
                int year = main.GetSystemControls().default_bgm_year.Value;
                txtBgmYear.Text = year.ToString();
                txtBgmYear.MinValue = year - 10;
                txtBgmYear.MaxValue = year + 1;
                lblBgmYear.Text = year.ToString();
                //===========================
                
                UpdateUI1("ViewAll");

                loadDDLFilterEventSeq();
                LoadDDLFilterBgmSourceSeq();
                LoadDDLFilterWorkAreaSeq();
                LoadRBLBgmExpGrpSeq();
                LoadRBLBorrowTypeSeqSeq();
                GetOptionProduct();
                //GetOptionProduct1();
                lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
                rblEventSeq_SelectedIndexChanged(null, null);
            }
        }

        protected void LoadRadGrid1()
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strWorkAreaSeq = ddlFilterWorkAreaSeq.SelectedValue;
            string strEventSeq = ddlFilterEventSeq.SelectedValue;
            string strContactSeq = null;
            string strRecordStatus = (cmdArival.CssClass == "LinkButtonBigBorder" ? "W" : "A");
            //string strEmpSeq = Session["EmpSeq"].ToString();
            RadGrid1.DataSource = mr.GetFull(strBgmSourceSeq, strBgmYear, strWorkAreaSeq, strEventSeq
                , strContactSeq, null, strRecordStatus, false);
        }

        protected void LoadGrdMoneyRequestDtls()
        {
            string strMoneyReqSeq = lblMoneyReqSeq.Text;

            if (strMoneyReqSeq.Length == 0)
            {
                strMoneyReqSeq = null;
            }

            grdMoneyRequestDtls.DataSource = mrd.GetExpFromProject(lblBgmProjOperSeq.Text
                , ddlFilterBgmSourceSeq.SelectedValue, rblBgmExpGrpSeq.SelectedValue, strMoneyReqSeq);
            grdMoneyRequestDtls.DataBind();

            grdMoneyRequestDtls.Columns.FindByUniqueName("button").Visible = lblRecordStatus.Text != "A";
        }

        protected void LoadGrdMoneyRequestDtls2()
        {
            string strMoneyReqSeq = lblMoneyReqSeq.Text;

            if (strMoneyReqSeq.Length == 0)
            {
                strMoneyReqSeq = null;
            }

            grdMoneyRequestDtls.DataSource = mrd.GetExpFromProject(ddlBgmProjOperSeq.SelectedValue
                , ddlFilterBgmSourceSeq.SelectedValue, rblBgmExpGrpSeq.SelectedValue, strMoneyReqSeq);
            grdMoneyRequestDtls.DataBind();

            grdMoneyRequestDtls.Columns.FindByUniqueName("button").Visible = lblRecordStatus.Text != "A";
        }

        protected void loadDDLFilterEventSeq()
        {
            ddlFilterEventSeq.DataSource = ev.GetList();
            ddlFilterEventSeq.DataBind();

            main.InsertEmptyDDLAll(ddlFilterEventSeq);
            ddlFilterEventSeq.SelectedIndex = 0;
        }

        protected void LoadDDLFilterBgmSourceSeq()
        {
            ddlFilterBgmSourceSeq.DataSource = source.GetFull(true);
            ddlFilterBgmSourceSeq.DataBind();

            ddlFilterBgmSourceSeq.SelectedIndex = 0;
            rblUseAdvance.Items[0].Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
            LoadRBLBorrowTypeSeqSeq();
        }

        protected void LoadDDLFilterWorkAreaSeq()
        {
            ddlFilterWorkAreaSeq.DataSource = area.GetFull();
            ddlFilterWorkAreaSeq.DataBind();
            main.InsertEmptyDDLAll(ddlFilterWorkAreaSeq);

            ddlFilterWorkAreaSeq.SelectedIndex = 0;
        }

        protected void LoadRBLBorrowTypeSeqSeq()
        {
            rblBorrowTypeSeq.DataSource = bt.GetList(ddlFilterBgmSourceSeq.SelectedValue);
            rblBorrowTypeSeq.DataBind();

            if (rblBorrowTypeSeq.Items.Count > 0)
                rblBorrowTypeSeq.SelectedIndex = 0;
        }

        protected void LoadRBLBgmExpGrpSeq()
        {
            rblBgmExpGrpSeq.DataSource = expgrp.GetList(null);
            rblBgmExpGrpSeq.DataBind();

            if (rblBgmExpGrpSeq.Items.Count > 0)
                rblBgmExpGrpSeq.SelectedIndex = 1;
        }

        //protected void LoadDDLBgmProjOperSeq()
        //{
        //    string strJobsiteSeq = Session["UserInternalJobsiteSeq"].ToString();
        //    if (strJobsiteSeq == sc.GetInfo().finance_job_site_seq.ToString())
        //    {
        //        strJobsiteSeq = null;
        //    }

        //    ddlBgmProjOperSeq.DataSource = oper.GetList(ddlFilterBgmSourceSeq.SelectedValue, txtBgmYear.Text
        //        , strJobsiteSeq, null, null, true, true);
        //    ddlBgmProjOperSeq.DataBind();
        //}

        protected void UpdateUI1(string strCommand)
        {
            switch (strCommand)
            {
                case "ViewAll":
                case "Insert":
                case "Update":
                    cmdViewAll1.Visible = false;
                    cmdAddNew1.Visible = true;
                    cmdEdit1.Visible = true;
                    cmdDelete1.Visible = true;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = false;
                    cmdSendMessage1.Visible = false;

                    PanelRadGrid1.Visible = true;
                    PanelEdit1.Visible = false;
                    PanelHeader.Visible = true;
                    pnlBgmExpDrp.Visible = true;
                    ddlBgmProjOperSeq.Visible = false;
                    pnlBtb2.Visible = true;

                    lblMode.Text = "แสดงข้อมูล";
                    break;
                case "AddNew":
                    cmdViewAll1.Visible = true;
                    cmdAddNew1.Visible = false;
                    cmdEdit1.Visible = false;
                    cmdDelete1.Visible = false;
                    cmdInsert1.Visible = true;
                    cmdUpdate1.Visible = false;
                    cmdSendMessage1.Visible = false;

                    PanelRadGrid1.Visible = false;
                    PanelEdit1.Visible = true;
                    PanelHeader.Visible = false;
                    rblEventSeq.Enabled = false;
                    pnlBgmExpDrp.Visible = false;
                    ddlBgmProjOperSeq.Visible = true;
                    lblBgmProjOperName.Visible = false;
                    pnlBtb2.Visible = false;

                    lblMode.Text = "เพิ่มรายการ";
                    break;
                case "Edit":
                    cmdViewAll1.Visible = true;
                    cmdAddNew1.Visible = false;
                    cmdEdit1.Visible = false;
                    cmdDelete1.Visible = false;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = true;
                    cmdSendMessage1.Visible = false;//lblRecordStatus.Text == "W" || lblRecordStatus.Text == "R";

                    PanelRadGrid1.Visible = false;
                    PanelEdit1.Visible = true;
                    PanelHeader.Visible = false;
                    rblEventSeq.Enabled = false;
                    pnlBgmExpDrp.Visible = true;
                    ddlBgmProjOperSeq.Visible = false;
                    lblBgmProjOperName.Visible = true;
                    pnlBtb2.Visible = true;

                    lblMode.Text = "แก้ไขรายการ";
                    break;
            }
        }

        protected void ClearControl1()
        {
            
        }

        protected void ClearControl2()
        {
            txtAmount.Text = "";
            ViewState["Amount"] = 0;
        }

        protected bool CheckData2()
        {
            bool bOK = true;
            string strError = "";
            string strAmount = txtAmount.Text;
            //string strExchangeRate = txtExchangeRate.Text;

            if (strAmount.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("จำนวนเงินที่ขอ");
            }
            //else if (strExchangeRate.Length == 0)
            //{
            //    bOK = false;
            //    strError = main.ErrorEmpty("อัตราแลกเปลี่ยน");
            //}

            if (!bOK)
                main.MessageAlert(Page, strError);

            return bOK;
        }

        protected bool CheckAmount(string strRemainAmount, string strAmount)
        {
            double dRemainAmount = (main.WebString(strRemainAmount).Length > 0 ? Convert.ToDouble(strRemainAmount) : 0);
            double dAmount = (strAmount.Length > 0 ? Convert.ToDouble(strAmount) : 0);
            bool bOK = dRemainAmount >= dAmount;

            if (!bOK)
            {

                main.MessageAlert(Page, string.Format("ยอดเงินไม่พอ (คงเหลือ {0}บาท, ใช้ {1}บาท)", strRemainAmount, strAmount));
            }
            return bOK;
        }

        //============================ control events ==============================

        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            //if (e.CommandName == "Select")
            //{
            //    GridDataItem item = (GridDataItem)e.Item;
            //    string strRecordStatus = mr.GetInfo(main.WebString(item["money_req_seq"].Text)).record_status;
            //    bool bApproved = strRecordStatus == "A";
            //    cmdDelete1.Enabled = bApproved;
            //}
        }

        protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if (!e.IsFromDetailTable)
            {
                LoadRadGrid1();
            }
        }

        protected void grdMoneyRequestDtls_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "AddExpense")
            {
                GridDataItem item = (GridDataItem)e.Item;
                lblMoneyReqDtlsSeq.Text = main.WebString(item["money_req_dtls_seq"].Text);
                lblBgmProjOperExpSeq.Text = main.WebString(item["m_bgm_projectoperationexpense.bgm_proj_oper_exp_seq"].Text);
                lblBgmExpName.Text = main.WebString(item["m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_name"].Text);
                lblRemainAmount.Text = main.WebString(item["m_bgm_projectoperationexpense.remain_amount"].Text);
                lblBgmExpSeq.Text = main.WebString(item["m_bgm_projectoperationexpense.m_bgm_projectexpense.bgm_exp_seq"].Text);

                //lblBgmSourceSeq.Text = ddlFilterBgmSourceSeq.SelectedValue;
                //lblBgmExpGrpSeq.Text = rblBgmExpGrpSeq.SelectedValue;

                txtAmount.Text = main.WebString(item["amount"].Text);
                ViewState["Amount"] = main.ConvertNullDouble(txtAmount.Text);
                string strBgmExpGrpSeq = rblBgmExpGrpSeq.SelectedValue;//main.WebString(item["m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.bgm_exp_grp_seq"].Text);
                int nExpRateCount = Convert.ToInt32(item["m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.exp_rate_count"].Text);

                if (strBgmExpGrpSeq == "3")
                {
                    lblIcmResItemSeq.Text = main.WebString(item["m_bgm_projectoperationexpense.icm_res_item_seq"].Text);

                    DataRow dr = icmItem.GetInfo(Convert.ToInt32(lblIcmResItemSeq.Text));

                    lblIcmResItemCode.Text = dr["icm_res_item_code"].ToString();
                    lblIcmResItemName.Text = dr["icm_res_item_name"].ToString();

                    lblUnitPriceProj.Text = main.WebString(item["m_bgm_projectoperationexpense.unit_price"].Text);
                    lblUnitQtyProj.Text = main.WebString(item["m_bgm_projectoperationexpense.unit_qty"].Text);
                    txtAmount.Text = main.WebString(item["m_bgm_projectoperationexpense.bath_amount"].Text);
                    PanelInv.Visible = true;
                    PanelExpRate.Visible = false;

                    txtAmount.Enabled = false;
                }
                else if (nExpRateCount > 0)
                {
                    PanelInv.Visible = false;
                    SetQty(lblBgmExpSeq.Text);

                    Nullable<int> nClassCount = main.ConvertNullInt(item["m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.class_count"].Text == "&nbsp;" ? "0" : item["m_bgm_projectoperationexpense.m_bgm_projectexpense.m_bgm_mas_expense.class_count"].Text);

                    if (nClassCount != null)
                    {
                        if (nClassCount > 0)
                        {
                            PanelExpRate.Visible = false;
                            PanelExpRateEmp.Visible = true;
                            LoadRepeaterExpRateEmp();
                        }
                        else
                        {
                            PanelExpRate.Visible = true;
                            PanelExpRateEmp.Visible = false;
                            //LoadRepeaterFilter();
                            LoadRepeaterExpRate();
                        }
                    }

                    txtAmount.Enabled = false;
                }
                else
                {
                    PanelInv.Visible = false;
                    PanelExpRate.Visible = false;
                    PanelExpRateEmp.Visible = false;
                    txtAmount.Enabled = true;
                }

                bool bAddNew = (lblMoneyReqDtlsSeq.Text.Length == 0);
                cmdInsert2.Visible = bAddNew;
                cmdUpdate2.Visible = !bAddNew;
                PanelProjOperExp.Visible = true;
                PanelProjOperExp.Enabled = true;
            }

            PanelOpacity.Visible = true;
            Panel1.Enabled = false;
            PanelControl1.Enabled = false;
            HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("body");
            body.Attributes["class"] = "disableScrollBar";
        }

        protected void grdMoneyRequestDtls_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                bool bCanEdit = (lblRecordStatus.Text != "A" && lblRecordStatus.Text != "D");
                ((LinkButton)e.Item.FindControl("cmdAddExpense")).Enabled = bCanEdit;
            }
        }

        protected void SetQty(string strBgmExpSeq)
        {
            //ViewState["bRelate"] = rateType.GetRelate(strBgmExpSeq);
        }

        //protected void LoadRepeaterFilter()
        //{
        //    string strBgmExpSeq = lblBgmExpSeq.Text;

        //    RepeaterFilter.DataSource = rateTypeGrp.GetFull(strBgmExpSeq);
        //    RepeaterFilter.DataBind();
        //}

        //protected void RepeaterFilter_ItemDataBound(object sender, RepeaterItemEventArgs e)
        //{
        //    if (e.Item is RepeaterItem)
        //    {
        //        if (e.Item.ItemType != ListItemType.Header)
        //        {
        //            RepeaterItem dataItem = (RepeaterItem)e.Item;
        //            Label lbl = (Label)dataItem.FindControl("lblExpRateTypeGrpSeq");
        //            //Label lbl2 = (Label)dataItem.FindControl("lblExpRateMapSeq");
        //            RadComboBox ddl = (RadComboBox)dataItem.FindControl("ddlExpRateTypeSeq");

        //            ddl.DataSource = rateType.GetList(lbl.Text);
        //            ddl.DataBind();

        //            main.InsertEmptyDDLAll(ddl);
        //            ddl.SelectedIndex = 0;
        //        }
        //    }
        //}

        protected void LoadRepeaterExpRate()
        {
            string strMoneyReqDtlsSeq = lblMoneyReqDtlsSeq.Text;
            string strBgmProjOperExpSeq = lblBgmProjOperExpSeq.Text;
            //string strBgmSourceSeq = lblBgmSourceSeq.Text;
            string strSeq;
            //string[] strExpRateTypeSeq = new string[RepeaterFilter.Items.Count];
            int j = 0;

            //for (int i = 0; i < strExpRateTypeSeq.Length; i++)
            //{
            //    RadComboBox ddl = (RadComboBox)RepeaterFilter.Items[i].FindControl("ddlExpRateTypeSeq");
            //    strSeq = ddl.SelectedValue;

            //    if (strSeq.Length > 0)
            //    {
            //        strExpRateTypeSeq[j] = strSeq;
            //        j++;
            //    }
            //}

            if (strMoneyReqDtlsSeq.Length > 0)
            {
                RepeaterExpRate.DataSource = mrRate.GetFull(strMoneyReqDtlsSeq, null);
            }
            else
            {
                RepeaterExpRate.DataSource = mrRate.GetFull2(strBgmProjOperExpSeq, null);
            }

            RepeaterExpRate.DataBind();
        }

        protected void LoadRepeaterExpRateEmp()
        {
            string strMoneyReqSeq = lblMoneyReqSeq.Text;
            //string strMoneyReqDtlsSeq = lblMoneyReqDtlsSeq.Text;
            //string strBgmProjOperExpSeq = lblBgmProjOperExpSeq.Text;
            //string strBgmSourceSeq = ddlBgmSourceSeq.SelectedValue;
            //string strSeq;

            RepeaterExpRateEmp.DataSource = mrTrav.GetFull(strMoneyReqSeq);
            RepeaterExpRateEmp.DataBind();
        }

        protected void RepeaterExpRate_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item is RepeaterItem)
            {
                if (e.Item.ItemType != ListItemType.Header)
                {
                    RepeaterItem dataItem = e.Item;
                    RadNumericTextBox txtMan = (RadNumericTextBox)dataItem.FindControl("txtMan");
                    RadNumericTextBox txtDay = (RadNumericTextBox)dataItem.FindControl("txtDay");
                    RadNumericTextBox txtHour = (RadNumericTextBox)dataItem.FindControl("txtHour");
                    RadNumericTextBox txtMinute = (RadNumericTextBox)dataItem.FindControl("txtMinute");
                    Label lblExpRateName = (Label)dataItem.FindControl("lblExpRateName");
                    Label lblExpRateDescr = (Label)dataItem.FindControl("lblExpRateDescr");
                    Label lblMan = (Label)dataItem.FindControl("lblMan");
                    Label lblDay = (Label)dataItem.FindControl("lblDay");
                    Label lblHour = (Label)dataItem.FindControl("lblHour");
                    Label lblMinute = (Label)dataItem.FindControl("lblMinute");
                    bool[] bRelate = (bool[])ViewState["bRelate"];

                    lblExpRateName.ToolTip = lblExpRateDescr.Text;

                    if (bRelate[0])
                    {
                        txtMan.Visible = true;
                        lblMan.Visible = true;
                    }

                    if (bRelate[1])
                    {
                        txtDay.Visible = true;
                        lblDay.Visible = true;
                    }

                    if (bRelate[2])
                    {
                        txtHour.Visible = true;
                        lblHour.Visible = true;
                    }

                    if (bRelate[3])
                    {
                        txtMinute.Visible = true;
                        lblMinute.Visible = true;
                    }
                }
            }
        }

        protected void RepeaterExpRateEmp_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item is RepeaterItem)
            {
                if (e.Item.ItemType != ListItemType.Header)
                {
                    RepeaterItem item = e.Item;
                    Label lblEmpSeq = (Label)item.FindControl("lblEmpSeq");
                    string strMoneyReqDtlsSeq = lblMoneyReqDtlsSeq.Text;
                    string strBgmProjOperExpSeq = lblBgmProjOperExpSeq.Text;
                    string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
                    string strBgmExpSeq = lblBgmExpSeq.Text;
                    M_FIM_MoneyRequestDtlsRates rateInfo = mrRate.GetInfo(strMoneyReqDtlsSeq, lblEmpSeq.Text);

                    Label lblClassSeq = (Label)item.FindControl("lblClassSeq");
                    Label lblMoneyReqDtlsRateSeq = (Label)item.FindControl("lblMoneyReqDtlsRateSeq");
                    RadComboBox ddlExpRateSeq = (RadComboBox)item.FindControl("ddlExpRateSeq");
                    RadNumericTextBox txtAmount = (RadNumericTextBox)item.FindControl("txtAmount");
                    RadNumericTextBox txtMan = (RadNumericTextBox)item.FindControl("txtMan");
                    RadNumericTextBox txtDay = (RadNumericTextBox)item.FindControl("txtDay");
                    RadNumericTextBox txtHour = (RadNumericTextBox)item.FindControl("txtHour");
                    RadNumericTextBox txtMinute = (RadNumericTextBox)item.FindControl("txtMinute");
                    Label lblTotalAmount = (Label)item.FindControl("lblTotalAmount");
                    Label lblMan = (Label)item.FindControl("lblMan");
                    Label lblDay = (Label)item.FindControl("lblDay");
                    Label lblHour = (Label)item.FindControl("lblHour");
                    Label lblMinute = (Label)item.FindControl("lblMinute");
                    HtmlInputHidden hAmountMin = (HtmlInputHidden)item.FindControl("hAmountMin");
                    HtmlInputHidden hAmountMax = (HtmlInputHidden)item.FindControl("hAmountMax");
                    LinkButton cmdAmountMax = (LinkButton)item.FindControl("cmdAmountMax");

                    //bool[] bRelate = rateType.GetRelate(strBgmExpSeq);

                    //if (bRelate[0])
                    //{
                    //    txtMan.Visible = true;
                    //    lblMan.Visible = true;
                    //}

                    //if (bRelate[1])
                    //{
                    //    txtDay.Visible = true;
                    //    lblDay.Visible = true;
                    //}

                    //if (bRelate[2])
                    //{
                    //    txtHour.Visible = true;
                    //    lblHour.Visible = true;
                    //}

                    //if (bRelate[3])
                    //{
                    //    txtMinute.Visible = true;
                    //    lblMinute.Visible = true;
                    //}

                    //ddlExpRateSeq.DataSource = rateType.GetClassExpRateList(lblClassSeq.Text, strBgmSourceSeq, strBgmExpSeq);
                    //ddlExpRateSeq.DataBind();

                    if (rateInfo == null)
                    {
                        ddlExpRateSeq.SelectedIndex = 0;
                        ddlExpRateSeq_SelectedIndexChanged(ddlExpRateSeq, null);
                        txtMan.Text = "1";
                        txtDay.Text = "1";
                        txtHour.Text = "1";
                        txtMinute.Text = "1";
                    }
                    else
                    {
                        lblMoneyReqDtlsRateSeq.Text = rateInfo.money_req_dtls_rate_seq.ToString();
                        ddlExpRateSeq.SelectedValue = rateInfo.exp_rate_seq.ToString();
                        ddlExpRateSeq_SelectedIndexChanged(ddlExpRateSeq, null);
                        txtAmount.Text = rateInfo.amount.Value.ToString("#,##0.00");
                        txtMan.Text = rateInfo.man.ToString();
                        txtDay.Text = rateInfo.day.ToString();
                        txtHour.Text = rateInfo.hour.ToString();
                        txtMinute.Text = rateInfo.minute.ToString();
                        lblTotalAmount.Text = rateInfo.total_amount.Value.ToString("#,##0.00");
                    }
                }
            }
        }

        protected void ddlExpRateSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            RadComboBox ddlExpRateSeq = (RadComboBox)o;
            RepeaterItem item = (RepeaterItem)ddlExpRateSeq.Parent;
            HtmlInputHidden hAmountMin = (HtmlInputHidden)item.FindControl("hAmountMin");
            HtmlInputHidden hAmountMax = (HtmlInputHidden)item.FindControl("hAmountMax");
            LinkButton cmdAmountMax = (LinkButton)item.FindControl("cmdAmountMax");
            string strExpRateSeq = ddlExpRateSeq.SelectedValue;
            M_FIM_MAS_ExpenseRates info = rate.GetInfo(strExpRateSeq);

            hAmountMin.Value = info.amount_min.ToString();
            hAmountMax.Value = info.amount_max.ToString();
            cmdAmountMax.Text = "ไม่เกิน " + info.amount_max.ToString();
        }

        //protected void ddlCurrencySeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        //{
        //    PanelExchangeRate.Visible = ddlCurrencySeq.SelectedValue != main.GetSystemControls().default_currency_seq.ToString();

        //    if (!PanelExchangeRate.Visible)
        //    {
        //        txtExchangeRate.Text = "1";
        //        lblAmountBath.Text = txtAmount.Text;
        //    }
        //}

        protected void cmdAmountMax_Click(object sender, EventArgs e)
        {
            RepeaterItem item = (RepeaterItem)((LinkButton)sender).Parent;

            ((RadNumericTextBox)item.FindControl("txtAmount")).Text = ((HtmlInputHidden)item.FindControl("hAmountMax")).Value;
            CalculateTotalAmount(sender);
        }

        protected void txtAmount_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount(sender);
        }

        protected void txtMan_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount(sender);
        }

        protected void txtDay_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount(sender);
        }

        protected void txtHour_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount(sender);
        }

        protected void txtMinute_TextChanged(object sender, EventArgs e)
        {
            CalculateTotalAmount(sender);
        }

        //protected void txtExchangeRate_TextChanged(object sender, EventArgs e)
        //{
        //    double dAmount = 0;
        //    double dExchangeRate = 0;

        //    if (double.TryParse(txtAmount.Text, out dAmount))
        //    {
        //        if (double.TryParse(txtExchangeRate.Text, out dExchangeRate))
        //        {
        //            lblAmountBath.Text = (dAmount * dExchangeRate).ToString("#,##0.00");
        //        }
        //    }
        //}

        protected void ddlExpRateTypeSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRepeaterExpRate();
        }

        protected void cmdViewAll1_Click(object sender, EventArgs e)
        {
            UpdateUI1("ViewAll");
            ClearControl1();
        }

        protected void cmdAddNew1_Click(object sender, EventArgs e)
        {
            string strBgmMonth;
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;

            strBgmMonth = main.GetBgmMonth(strBgmSourceSeq, DateTime.Today).ToString();
            
            UpdateUI1("AddNew");
            //FIM_MoneyRequestDtls1.LoadRoot("-1", ddlFilterBgmSourceSeq.SelectedValue, txtBgmYear.Text, strBgmMonth, 400, 600);
        }

        protected void cmdEdit1_Click(object sender, EventArgs e)
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                UpdateUI1("Edit");

                string strMoneyReqSeq = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["money_req_seq"].Text;

                var payInfo = pay.GetInfoFromMoneyReqSeq(strMoneyReqSeq);

                if (payInfo != null)
                {
                    lblPayRefNo.Text = payInfo.ref_no;
                }
                else
                {
                    lblPayRefNo.Text = "";
                }

                M_FIM_MoneyRequests info = mr.GetInfo(strMoneyReqSeq);
                string strEventSeq = info.event_seq.ToString();
                string strBgmProjOperSeq = info.bgm_proj_oper_seq.ToString();
                string strBgmSourceSeq = info.bgm_source_seq.ToString();
                string strBgmYear = info.bgm_year.ToString();
                string strBgmExpGrpSeq = info.bgm_exp_grp_seq.ToString();

                rblEventSeq.SelectedValue = strEventSeq;
                EventChanged(strMoneyReqSeq);

                rblBgmExpGrpSeq.Enabled = true;
                if (strBgmExpGrpSeq != null)
                {
                    if (strBgmExpGrpSeq.Length > 0)
                    {
                        rblBgmExpGrpSeq.SelectedValue = strBgmExpGrpSeq;
                        rblBgmExpGrpSeq.Enabled = false;
                    }
                }

                lblMoneyReqSeq.Text = strMoneyReqSeq;
                lblBgmProjOperSeq.Text = strBgmProjOperSeq;
                lblBgmProjOperName.Text = info.bgm_proj_oper_name;
                lblBgmProjOperCode.Text = info.bgm_proj_oper_code;
                lblRecordStatus.Text = info.record_status;
                txtMoneyReqName.Text = info.money_req_name;
                dpMoneyReqDate.SetValue(info.money_req_date);

                cmdUpdate1.Visible = lblRecordStatus.Text == "W" || lblRecordStatus.Text == "R";
                cmdSendMessage1.Visible = lblRecordStatus.Text == "W" || lblRecordStatus.Text == "R";

                switch (strEventSeq)
                {
                    case "11":
                        PanelBorrow.Visible = false;
                        PanelDN.Visible = true;
                        PanelSalary.Visible = false;
                        PanelRequest.Visible = false;

                        DBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);
                        string strIcmDnSeq = info.icm_dn_seq.ToString();
                        //string strSQL = "SELECT dn.ICM_DN_ITEM_SEQ"
                        //        + ", v.ICM_VAT_SEQ"
                        //        + ", CAST(CONCAT(v.ICM_VAT_NAME, ' อัตราภาษี ', b.VAT_PERCENT , ' %') as varchar) AS ICM_VAT_NAME"
                        //        + ", b.VAT_PERCENT"
                        //        + ", COALESCE(i.ICM_RES_ITEM_NAME, x.BGM_EXP_NAME) AS ITEM_NAME"
                        //        + ", dn.ITEM_DESCR"
                        //        + ", dn.ITEM_QTY"
                        //        + ", u.ICM_UNIT_NAME"
                        //        + ", 1 AS PO_ITEM_QTY"
                        //    //+ ", CAST(CONCAT(COALESCE(dn.ITEM_QTY, '0'), ' ', COALESCE(u.ICM_UNIT_NAME, 'รายการ')) as varchar) AS PO_ITEM_QTY"
                        //        + ", pi.NET_AMOUNT AS PO_NET_AMOUNT"
                        //        + ", dn.ITEM_PRICE_EXCLUDE_VAT"
                        //        + ", dn.ITEM_PRICE_INCLUDE_VAT"
                        //        + ", dn.EXCLUDE_VAT_AMOUNT"
                        //        + ", dn.VAT_AMOUNT"
                        //        + ", dn.NET_AMOUNT"
                        //    + " FROM ICM_DELIVERY_NOTE_ITEM dn"
                        //        + " INNER JOIN ICM_PURCHASE_ORDER_INSTALLMENT_ITEM pi ON dn.ICM_PO_INSTALL_ITEM_SEQ = pi.ICM_PO_INSTALL_ITEM_SEQ"
                        //        + " INNER JOIN ICM_BIDDER_QUOTATION q ON pi.ICM_BIDDER_QUO_SEQ = q.ICM_BIDDER_QUO_SEQ"
                        //        + " INNER JOIN ICM_BIDDER b ON q.ICM_BIDDER_SEQ = b.ICM_BIDDER_SEQ "
                        //        + " INNER JOIN ICM_PURCHASE_REQUEST_ITEM ri ON q.ICM_PR_ITEM_SEQ = ri.ICM_PR_ITEM_SEQ "
                        //        + " INNER JOIN BGM_MAS_EXPENSE x ON ri.BGM_EXP_SEQ = x.BGM_EXP_SEQ "
                        //        + " LEFT JOIN ICM_MAS_RESOURCE_ITEM i ON ri.ICM_RES_ITEM_SEQ = i.ICM_RES_ITEM_SEQ "
                        //        + " LEFT JOIN ICM_MAS_UNIT u ON i.ICM_UNIT_SEQ = u.ICM_UNIT_SEQ "
                        //        + " INNER JOIN ICM_SYS_VAT v ON b.ICM_VAT_SEQ = v.ICM_VAT_SEQ "
                        //    + " WHERE dn.ICM_DN_SEQ = " + strIcmDnSeq;
                        string strSQL = "SELECT dn.DnItemId as ICM_DN_ITEM_SEQ "
                             + ", v.LookUpId as ICM_VAT_SEQ"
                             + ", CAST(CONCAT(v.LookUpName, ' อัตราภาษี ', b.VatPercent , ' %') as varchar) AS ICM_VAT_NAME"
                             + ", b.VatPercent as VAT_PERCENT "
                             + ", COALESCE(i.Name, x.bgm_exp_name) AS ITEM_NAME"
                             + ", dn.Descr as ITEM_DESCR"
                             + ", dn.ItemQty as ITEM_QTY"
                             + ", u.Name as ICM_UNIT_NAME"
                             + ", 1 AS PO_ITEM_QTY, pi.NetAmount AS PO_NET_AMOUNT "
                             + ", dn.ItemPriceExcludeVat as ITEM_PRICE_EXCLUDE_VAT"
                             + ", dn.ItemPriceIncludeVat as ITEM_PRICE_INCLUDE_VAT"
                             + ", dn.ExcludeVatAmount as EXCLUDE_VAT_AMOUNT"
                             + ", dn.VatAmount as VAT_AMOUNT"
                             + ", dn.NetAmount as NET_AMOUNT"
                             + " FROM ICMDELIVERYNOTEITEM dn"
                             + " LEFT JOIN ICMPURCHASEORDERINSTALLMENTITEM pi ON dn.PoInstallItemId = pi.PoInstallItemId"
                             + " LEFT JOIN ICMBIDDERQUOTATION q ON pi.BidderQuoId = q.BidderQuoId"
                             + " LEFT JOIN ICMBIDDER b ON q.BidderId = b.BidderId"
                             + " LEFT JOIN ICMPURCHASEREQUESTITEM ri ON q.PrItemId = ri.PrItemId"
                             + " LEFT JOIN BGM_MAS_EXPENSE x ON ri.BgExpId = x.BGM_EXP_SEQ"
                             + " LEFT JOIN ICMMASRESOURCEITEM i ON ri.ResItemId = i.ResItemId"
                             + " LEFT JOIN ICMMASUNIT u ON i.UnitId = u.UnitId"
                             + " LEFT JOIN IcmMasLookUp v ON b.VatTypeId = v.LookUpId"
                             + " WHERE dn.DnId =" + strIcmDnSeq;
  
                        dbManager.Open();
                        DataTable dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                        dbManager.Dispose();

                        RadGridDN.DataSource = dtb;
                        RadGridDN.DataBind();
                        break;
                    case "12":
                        txtDocRefNo.Text = info.doc_ref_no;
                        break;
                    case "14":
                        break;
                    case "16":
                    case "18":
                        rblBorrowTypeSeq.SelectedValue = info.borrow_type_seq.ToString();
                        dpBorrowStartDate.SetValue(info.borrow_start_date);
                        dpBorrowEndDate.SetValue(info.borrow_end_date);
                        lblBorrowReturnDate.Text = (info.borrow_return_date != null ? info.borrow_return_date.Value.ToShortDateString() : "ยังไม่กำหนด");

                        if (bt.GetInfo(info.borrow_type_seq.ToString()).is_travel == "1")
                        {

                        }

                        break;
                    default :
                        break;
                }

                MoneyRequestApprover1.LoadMoneyRequestApprover(strMoneyReqSeq);
                LoadGrdMoneyRequestDtls();
                //FIM_MoneyRequestDtls1.LoadRoot(strMoneyReqSeq, strBgmSourceSeq, strBgmYear
                //    , strEventSeq, strBgmProjOperSeq, strBgmExpGrpSeq
                //    , Session["UserInternalJobsiteSeq"].ToString(), false);
            }
            else
            {
                main.MessageAlert(Page, "กรุณาเลือกรายการที่ต้องการแก้ไข");
            }
        }

        protected void cmdDelete1_Click(object sender, EventArgs e)
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                if (RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["record_status"].Text == "A")
                {
                    main.MessageAlert(Page, "ไม่สามารถลบรายการนี้ได้ เนื่องจากได้รับอนุมัติแล้ว");
                    return;
                }

                M_FIM_MoneyRequests info = new M_FIM_MoneyRequests();
                string strUserID = Session["EmpSeq"].ToString();
                DateTime dtNow = DateTime.Now;
                string strMoneyReqSeq = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["money_req_seq"].Text;

                info.money_req_seq = Convert.ToInt32(strMoneyReqSeq);
                info.updated_by = main.ConvertNullInt(strUserID);
                info.updated_when = main.ConvertNullDateTime(dtNow);

                mr.Delete(info);

                LoadRadGrid1();
                RadGrid1.DataBind();
            }
        }

        //protected void cmdApprove_Click(object sender, EventArgs e)
        //{
        //    M_FIM_MoneyRequests info = new M_FIM_MoneyRequests();
        //    string strUserID = Session["EmpSeq"].ToString();
        //    DateTime dtNow = DateTime.Now;
        //    string strMoneyReqSeq = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["money_req_seq"].Text;
        //    info.money_req_seq = Convert.ToInt32(strMoneyReqSeq);
        //    info.updated_by = main.ConvertNullInt(strUserID);
        //    info.updated_when = main.ConvertNullDateTime(dtNow);
        //    info.record_status = "A";

        //    string problemMessage;
        //    mr.ChangeStatus(info, out problemMessage);
        //    if(!string.IsNullOrEmpty(problemMessage)) RadAjaxManager.GetCurrent(Page).Alert(problemMessage);


        //    IList<M_FIM_MoneyRequestDtls> mrdInfo = mrd.GetFull(strMoneyReqSeq);
        //    for (int i = 0; i < mrdInfo.Count; i++)
        //    {
        //        M_FIM_MoneyRequestDtls expInfo = mrdInfo[i];
        //        M_BGM_ProjectOperationReport reportInfo = new M_BGM_ProjectOperationReport();
        //        reportInfo.money_req_dtls_seq = expInfo.money_req_dtls_seq;
        //        reportInfo.used_amount = expInfo.amount;
        //        reportInfo.cal_amount = -expInfo.amount;
        //        reportInfo.rpt_type = 5;//กันเงิน
        //        reportInfo.created_by = main.ConvertNullInt(strUserID);
        //        reportInfo.created_when = DateTime.Now;
        //        operRpt.Insert(reportInfo);
        //    }

        //    LoadRadGrid1();
        //    RadGrid1.DataBind();
        //    UpdateUI1("ViewAll");
        //    ClearControl1();
        //}

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            string strMoneyReqSeq = "";

            switch (rblEventSeq.SelectedValue)
            {
                case "11" :
                    //bOK = MoneyRequestDN1.Insert();
                    break;
                case "12" :
                    //bOK = MoneyRequest1.Insert();
                    break;
                case "14" :
                    M_FIM_MoneyRequests model = new M_FIM_MoneyRequests();
                    model.bgm_source_seq = main.ConvertNullInt(ddlFilterBgmSourceSeq.SelectedValue);
                    model.bgm_year = main.ConvertNullInt(txtBgmYear.Text);
                    model.work_area_seq = main.ConvertNullInt(ddlFilterWorkAreaSeq.SelectedValue);
                    model.bgm_exp_grp_seq = null;
                    model.event_seq = main.ConvertNullInt(rblEventSeq.SelectedValue);
                    model.money_req_date = dpMoneyReqDate.GetDateValue();
                    model.use_advance = "0";
                    model.advance_bgm_source_seq = null;
                    model.ref_no = null;
                    model.doc_ref_no = null;
                    model.money_req_name = txtMoneyReqName.Text;
                    model.money_req_name_plus = null;
                    model.bgm_proj_oper_seq = main.ConvertNullInt(ddlBgmProjOperSeq.SelectedValue);
                    model.emp_seq = main.ConvertNullInt(Session["EmpSeq"]);
                    model.job_site_seq = main.ConvertNullInt(Session[""]);
                    model.allow = "1";
                    model.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                    model.created_when = DateTime.Now;
                    model.record_status = "W";

                    strMoneyReqSeq = mr.Insert(model);

                    break;
                case "16" :
                case "18" :
                    //bOK = MoneyRequestLoan1.Insert();
                    break;
            }

            if (strMoneyReqSeq.Length > 0)
            {
                //UpdateUI1("Update");
                LoadRadGrid1();
                RadGrid1.DataBind();

                foreach(GridDataItem item in RadGrid1.Items)
                {
                    if (strMoneyReqSeq == main.WebString(item["money_req_seq"].Text))
                    {
                        item.Selected = true;
                        cmdEdit1_Click(null, null);
                        return;
                    }
                }

                UpdateUI1("ViewAll");
            }
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            bool bOK = true;

            switch (rblEventSeq.SelectedValue)
            {
                case "11":
                    //bOK = MoneyRequestDN1.Update();
                    break;
                case "12":
                    //bOK = MoneyRequest1.Update();
                    break;
                case "14":
                    //bOK = MoneyRequestSalaries1.Update();
                    break;
                case "16":
                case "18":
                    //bOK = MoneyRequestLoan1.Update();
                    break;
            }

            if (bOK)
            {
                UpdateUI1("Update");
                LoadRadGrid1();
                RadGrid1.DataBind();
            }
        }

        protected void cmdPrint1_Click(object sender, EventArgs e)
        {
            //if (RadGrid1.SelectedItems.Count > 0)
            //{
            //    string strSeq = Session["ReceiveSeq"].ToString();

            //    main.SetupReport("Receipt", strSeq);
            //}
        }

        protected void cmdInsert2_Click(object sender, EventArgs e)
        {
            if (!CheckData2())
                return;

            if (!CheckAmount(lblRemainAmount.Text, txtAmount.Text))
                return;

            Nullable<int> nBgmProjOperExpSeq = main.ConvertNullInt(lblBgmProjOperExpSeq.Text);
            Nullable<int> nMoneyReqSeq = main.ConvertNullInt(lblMoneyReqSeq.Text);
            Nullable<int> nBgmExpGrpSeq = main.ConvertNullInt(rblBgmExpGrpSeq.SelectedValue);
            Nullable<double> dAmount = main.ConvertNullDouble(txtAmount.Text);
            //Nullable<double> dBathAmount = main.ConvertNullDouble(lblAmountBath.Text);
            Nullable<int> nEmpSeq = main.ConvertNullInt(Session["EmpSeq"]);

            M_FIM_MoneyRequests reqInfo = new M_FIM_MoneyRequests();
            reqInfo.money_req_seq = nMoneyReqSeq.Value;
            reqInfo.bgm_exp_grp_seq = nBgmExpGrpSeq;
            mr.UpdateBgmExpGrpSeq(reqInfo);

            M_FIM_MoneyRequestDtls info = new M_FIM_MoneyRequestDtls();
            info.money_req_seq = nMoneyReqSeq;
            info.bgm_proj_oper_exp_seq = nBgmProjOperExpSeq;
            info.amount = dAmount;

            //if (PanelInv.Visible)
            //{
            //    info.unit_price = main.ConvertNullDouble(lblUnitPriceProj.Text);
            //    info.unit_qty = main.ConvertNullInt(lblUnitQtyProj.Text);
            //}
            //else
            //{
            //    info.unit_price = null;
            //    info.unit_qty = null;
            //}

            info.created_by = nEmpSeq;
            info.created_when = DateTime.Today;
            int nMoneyReqDtlsSeq = Convert.ToInt32(mrd.Insert(info));

            if (PanelExpRate.Visible || PanelExpRateEmp.Visible)
            {
                Repeater use = null;
                if (PanelExpRate.Visible)
                {
                    use = RepeaterExpRate;
                }
                else
                {
                    use = RepeaterExpRateEmp;
                }

                foreach (RepeaterItem item in use.Items)
                {
                    M_FIM_MoneyRequestDtlsRates rateInfo = new M_FIM_MoneyRequestDtlsRates();
                    string strTotalAmount = main.WebString(((Label)item.FindControl("lblTotalAmount")).Text);
                    string strMoneyReqDtlsRateSeq = main.WebString(((Label)item.FindControl("lblMoneyReqDtlsRateSeq")).Text);

                    if (main.ConvertNullDouble(strTotalAmount) > 0)
                    {
                        RadNumericTextBox txtMan = (RadNumericTextBox)item.FindControl("txtMan");
                        RadNumericTextBox txtDay = (RadNumericTextBox)item.FindControl("txtDay");
                        RadNumericTextBox txtHour = (RadNumericTextBox)item.FindControl("txtHour");
                        RadNumericTextBox txtMinute = (RadNumericTextBox)item.FindControl("txtMinute");

                        rateInfo.money_req_dtls_seq = nMoneyReqDtlsSeq;

                        rateInfo.amount = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtAmount")).Text);

                        if (PanelExpRateEmp.Visible)
                        {
                            rateInfo.emp_seq = main.ConvertNullInt(((Label)item.FindControl("lblEmpSeq")).Text);
                            rateInfo.class_seq = main.ConvertNullInt(((Label)item.FindControl("lblClassSeq")).Text);
                            rateInfo.exp_rate_seq = main.ConvertNullInt(((RadComboBox)item.FindControl("ddlExpRateSeq")).SelectedValue);
                        }
                        else
                        {
                            rateInfo.exp_rate_seq = main.ConvertNullInt(((Label)item.FindControl("lblExpRateSeq")).Text);
                        }

                        if (txtMan.Visible)
                        {
                            rateInfo.man = main.ConvertNullInt(((RadNumericTextBox)item.FindControl("txtMan")).Text);
                        }
                        else
                        {
                            rateInfo.man = null;
                        }

                        if (txtDay.Visible)
                        {
                            rateInfo.day = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtDay")).Text);
                        }
                        else
                        {
                            rateInfo.day = null;
                        }

                        if (txtHour.Visible)
                        {
                            rateInfo.hour = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtHour")).Text);
                        }
                        else
                        {
                            rateInfo.hour = null;
                        }

                        if (txtMinute.Visible)
                        {
                            rateInfo.minute = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtMinte")).Text);
                        }
                        else
                        {
                            rateInfo.minute = null;
                        }

                        if (strMoneyReqDtlsRateSeq.Length == 0)
                        {
                            rateInfo.created_by = nEmpSeq;
                            rateInfo.created_when = DateTime.Today;
                            mrRate.Insert(rateInfo);
                        }
                        else
                        {
                            rateInfo.money_req_dtls_rate_seq = main.ConvertNullInt(strMoneyReqDtlsRateSeq);
                            rateInfo.updated_by = nEmpSeq;
                            rateInfo.updated_when = DateTime.Today;
                            mrRate.Update(rateInfo);
                        }
                    }
                    else if (strMoneyReqDtlsRateSeq.Length > 0)
                    {
                        rateInfo.money_req_dtls_rate_seq = main.ConvertNullInt(strMoneyReqDtlsRateSeq);
                        rateInfo.updated_by = nEmpSeq;
                        rateInfo.updated_when = DateTime.Today;
                        mrRate.Delete(rateInfo);
                    }
                }
            }

            ClearControl2();
            cmdUpdate2.Visible = false;
            PanelProjOperExp.Visible = false;
            PanelOpacity.Visible = false;
            Panel1.Enabled = true;
            PanelControl1.Enabled = true;
            LoadGrdMoneyRequestDtls();
            rblBgmExpGrpSeq.Enabled = false;
        }

        protected void cmdUpdate2_Click(object sender, EventArgs e)
        {
            if (!CheckData2())
            { 
                return;
            }

            if (!CheckAmount(lblRemainAmount.Text, txtAmount.Text))
            {
                return;
            }

            int nMoneyReqDtlsSeq = Convert.ToInt32(lblMoneyReqDtlsSeq.Text);
            Nullable<int> nBgmProjOperExpSeq = main.ConvertNullInt(lblBgmProjOperExpSeq.Text);
            Nullable<int> nMoneyReqSeq = main.ConvertNullInt(lblMoneyReqSeq.Text);
            Nullable<double> dAmount = main.ConvertNullDouble(txtAmount.Text);
            Nullable<int> nEmpSeq = main.ConvertNullInt(Session["EmpSeq"]);

            M_FIM_MoneyRequestDtls info = new M_FIM_MoneyRequestDtls();
            info.money_req_dtls_seq = nMoneyReqDtlsSeq;
            info.money_req_seq = nMoneyReqSeq;
            info.bgm_proj_oper_exp_seq = nBgmProjOperExpSeq;
            info.amount = dAmount;

            info.updated_by = nEmpSeq;
            info.updated_when = DateTime.Today;

            mrd.Update(info);

            if (PanelExpRate.Visible || PanelExpRateEmp.Visible)
            {
                Repeater use = null;
                if (PanelExpRate.Visible)
                {
                    use = RepeaterExpRate;
                }
                else
                {
                    use = RepeaterExpRateEmp;
                }

                foreach (RepeaterItem item in use.Items)
                {
                    M_FIM_MoneyRequestDtlsRates rateInfo = new M_FIM_MoneyRequestDtlsRates();
                    string strTotalAmount = main.WebString(((Label)item.FindControl("lblTotalAmount")).Text);
                    string strMoneyReqDtlsRateSeq = main.WebString(((Label)item.FindControl("lblMoneyReqDtlsRateSeq")).Text);

                    if (main.ConvertNullDouble(strTotalAmount) > 0)
                    {
                        RadNumericTextBox txtMan = (RadNumericTextBox)item.FindControl("txtMan");
                        RadNumericTextBox txtDay = (RadNumericTextBox)item.FindControl("txtDay");
                        RadNumericTextBox txtHour = (RadNumericTextBox)item.FindControl("txtHour");
                        RadNumericTextBox txtMinute = (RadNumericTextBox)item.FindControl("txtMinute");

                        rateInfo.money_req_dtls_seq = nMoneyReqDtlsSeq;
                        rateInfo.amount = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtAmount")).Text);

                        if (PanelExpRate.Visible)
                        {
                            rateInfo.exp_rate_seq = main.ConvertNullInt(((Label)item.FindControl("lblExpRateSeq")).Text);
                        }
                        else
                        {
                            rateInfo.exp_rate_seq = main.ConvertNullInt(((RadComboBox)item.FindControl("ddlExpRateSeq")).SelectedValue);
                            rateInfo.emp_seq = main.ConvertNullInt(((Label)item.FindControl("lblEmpSeq")).Text);
                            rateInfo.class_seq = main.ConvertNullInt(((Label)item.FindControl("lblClassSeq")).Text);
                        }

                        if (txtMan.Visible)
                        {
                            rateInfo.man = main.ConvertNullInt(((RadNumericTextBox)item.FindControl("txtMan")).Text);
                        }
                        else
                        {
                            rateInfo.man = null;
                        }

                        if (txtDay.Visible)
                        {
                            rateInfo.day = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtDay")).Text);
                        }
                        else
                        {
                            rateInfo.day = null;
                        }

                        if (txtHour.Visible)
                        {
                            rateInfo.hour = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtHour")).Text);
                        }
                        else
                        {
                            rateInfo.hour = null;
                        }

                        if (txtMinute.Visible)
                        {
                            rateInfo.minute = main.ConvertNullDouble(((RadNumericTextBox)item.FindControl("txtMinte")).Text);
                        }
                        else
                        {
                            rateInfo.minute = null;
                        }

                        if (strMoneyReqDtlsRateSeq.Length == 0)
                        {
                            rateInfo.created_by = nEmpSeq;
                            rateInfo.created_when = DateTime.Today;
                            mrRate.Insert(rateInfo);
                        }
                        else
                        {
                            rateInfo.money_req_dtls_rate_seq = main.ConvertNullInt(strMoneyReqDtlsRateSeq);
                            rateInfo.updated_by = nEmpSeq;
                            rateInfo.updated_when = DateTime.Today;
                            mrRate.Update(rateInfo);
                        }
                    }
                    else if (strMoneyReqDtlsRateSeq.Length > 0)
                    {
                        rateInfo.money_req_dtls_rate_seq = main.ConvertNullInt(strMoneyReqDtlsRateSeq);
                        rateInfo.updated_by = nEmpSeq;
                        rateInfo.updated_when = DateTime.Today;
                        mrRate.Delete(rateInfo);
                    }
                }
            }

            ClearControl2();
            cmdInsert2.Visible = false;
            PanelProjOperExp.Visible = false;
            PanelOpacity.Visible = false;
            Panel1.Enabled = true;
            PanelControl1.Enabled = true;
            LoadGrdMoneyRequestDtls();
            //LoadRepeater4();
        }

        protected void cmdCancel2_Click(object sender, EventArgs e)
        {
            ClearControl2();
            PanelProjOperExp.Visible = false;
            PanelOpacity.Visible = false;
            Panel1.Enabled = true;
            PanelControl1.Enabled = true;
        }

        protected void rblEventSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            EventChanged("");
        }

        protected void EventChanged(string strMoneyReqSeq)
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            //string strBgmMonth = main.GetBgmMonth(main.WebString(strBgmSourceSeq), Convert.ToDateTime(txtMoneyReqDate.TextWithLiterals)).ToString();

            switch (rblEventSeq.SelectedValue)
            {
                case "11"://ซื้อ/จ้าง
                    PanelDN.Visible = true;
                    PanelSalary.Visible = false;
                    PanelRequest.Visible = false;
                    PanelBorrow.Visible = false;
                    break;
                case "12"://ชดใช้ใบสำคัญ
                case "17"://งบกลาง
                    PanelDN.Visible = false;
                    PanelSalary.Visible = false;
                    PanelRequest.Visible = true;
                    PanelBorrow.Visible = false;
                    break;
                case "14"://เงินเดือน
                    PanelDN.Visible = false;
                    PanelSalary.Visible = true;
                    PanelRequest.Visible = false;
                    PanelBorrow.Visible = false;
                    break;
                case "16"://เงินยืม
                case "18"://เงินยืมบัตรเครดิต
                    PanelDN.Visible = false;
                    PanelSalary.Visible = false;
                    PanelRequest.Visible = false;
                    PanelBorrow.Visible = true;
                    break;
            }
        }

        protected void ddlFilterBgmSourceSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
            rblUseAdvance.Items[0].Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
            LoadRadGrid1();
            RadGrid1.DataBind();
        }

        protected void ddlFilterWorkAreaSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRadGrid1();
            RadGrid1.DataBind();
        }

        protected void ddlFilterEventSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRadGrid1();
            RadGrid1.DataBind();
        }

        protected void txtBgmYear_TextChanged(object sender, EventArgs e)
        {
            lblBgmYear.Text = txtBgmYear.Text;
            LoadRadGrid1();
            RadGrid1.DataBind();
        }

        //==========================================================================

        protected void cmdArival_Click(object sender, EventArgs e)
        {
            cmdArival.CssClass = "LinkButtonBigBorder";
            cmdHistory.CssClass = "LinkButtonBigNoBorder";

            LoadRadGrid1();
            RadGrid1.DataBind();
        }

        protected void cmdHistory_Click(object sender, EventArgs e)
        {
            cmdArival.CssClass = "LinkButtonBigNoBorder";
            cmdHistory.CssClass = "LinkButtonBigBorder";

            LoadRadGrid1();
            RadGrid1.DataBind();
        }

        protected void ddlBgmProjOperSeq_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (grdMoneyRequestDtls.Visible)
            {
                LoadGrdMoneyRequestDtls2();
            }

            if (ddlBgmProjOperSeq.SelectedValue.Length > 0)
            {
                M_BGM_ProjectOperation model = oper.GetInfo(ddlBgmProjOperSeq.SelectedValue);
                lblBgmProjOperCode.Text = model.bgm_proj_oper_code;
            }
        }

        protected void CalculateTotalAmount(object sender)
        {
            RepeaterItem item = null;

            if (sender.GetType().Name == "RadNumericTextBox")
            {
                item = (RepeaterItem)((RadNumericTextBox)sender).Parent;
            }
            else if (sender.GetType().Name == "LinkButton")
            {
                item = (RepeaterItem)((LinkButton)sender).Parent;
            }

            HtmlInputHidden hAmountMin = (HtmlInputHidden)item.FindControl("hAmountMin");
            HtmlInputHidden hAmountMax = (HtmlInputHidden)item.FindControl("hAmountMax");
            RadNumericTextBox txtAmount = (RadNumericTextBox)item.FindControl("txtAmount");
            double dAmount = (txtAmount.Value != null ? txtAmount.Value.Value : 1);
            double dMin = (main.WebString(hAmountMin.Value) != "" ? Convert.ToDouble(hAmountMin.Value) : 0);
            double dMax = (main.WebString(hAmountMax.Value) != "" ? Convert.ToDouble(hAmountMax.Value) : 0);

            if (dAmount > dMax)
            {
                txtAmount.Text = dMax.ToString("#,##0.00");
                main.MessageAlert(Page, "จำนวนเงินมากกว่าอัตราค่าใช้จ่าย");
                return;
            }

            if (dAmount < dMin)
            {
                txtAmount.Text = dMin.ToString("#,##0.00");
                main.MessageAlert(Page, "จำนวนเงินน้อยกว่าอัตราค่าใช้จ่าย");
                return;
            }

            RadNumericTextBox txtMan = (RadNumericTextBox)item.FindControl("txtMan");
            RadNumericTextBox txtDay = (RadNumericTextBox)item.FindControl("txtDay");
            RadNumericTextBox txtHour = (RadNumericTextBox)item.FindControl("txtHour");
            RadNumericTextBox txtMinute = (RadNumericTextBox)item.FindControl("txtMinute");
            Label lblTotalAmount = (Label)item.FindControl("lblTotalAmount");
            double dTotalAmount = dAmount
                * (txtMan.Value != null ? txtMan.Value.Value : 1)
                * (txtDay.Value != null ? txtDay.Value.Value : 1)
                * (txtHour.Value != null ? txtHour.Value.Value : 1)
                * (txtMinute.Value != null ? txtMinute.Value.Value : 1);

            lblTotalAmount.Text = dTotalAmount.ToString("#,##0.00");
            CalculateSumAmount();
        }

        protected void CalculateSumAmount()
        {
            double dSumAmount = 0;

            if (RepeaterExpRate.Visible)
            {
                foreach (RepeaterItem item in RepeaterExpRate.Items)
                {
                    Label lblTotalAmount = (Label)item.FindControl("lblTotalAmount");
                    dSumAmount = dSumAmount + (lblTotalAmount.Text.Length > 0 ? Convert.ToDouble(lblTotalAmount.Text) : 0);
                }
            }
            else
            {
                foreach (RepeaterItem item in RepeaterExpRateEmp.Items)
                {
                    Label lblTotalAmount = (Label)item.FindControl("lblTotalAmount");
                    dSumAmount = dSumAmount + (lblTotalAmount.Text.Length > 0 ? Convert.ToDouble(lblTotalAmount.Text) : 0);
                }
            }

            txtAmount.Text = dSumAmount.ToString("#,##0.00");
            //lblAmountBath.Text = (dSumAmount * (txtExchangeRate.Visible ? (txtExchangeRate.Value.HasValue ? txtExchangeRate.Value.Value : 1) : 1)).ToString("#,##0.00");
        }

        protected void GetOptionProduct()
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strYear = txtBgmYear.Text;

            ddlBgmProjOperSeq.DataSource = ProjOper.GetList(strBgmSourceSeq, strYear, null, null, null, true, true);
            ddlBgmProjOperSeq.DataBind();
        }

        protected void rblBgmExpGrpSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlBgmProjOperSeq.Visible)
            {
                LoadGrdMoneyRequestDtls2();
            }
            else
            {
                LoadGrdMoneyRequestDtls();
            }
        }

        protected void cmdSendMessage1_Click(object sender, EventArgs e)
        {
            PanelMessageSend.Visible = true;
            ddlApprover.SelectedIndex = -1;
            lblAppClassName.Text = "";
            lblAppExecPosName.Text = "";
            lblAppJobsiteName.Text = "";
            lblAppPosName.Text = "";
            lblEmpSeq.Text = "";

            //if (lblRecordStatus.Text == "R")
            //{
            //    var model = send.GetLatestMessageStatus(lblMoneyReqSeq.Text, "fim_money_requests");
            //    lblApprovePathSeq.Text = model.approve_path_seq.ToString();
            //    //ddlApprover_ItemsRequested(null, null);
            //    ddlApprover.SelectedValue = model.to_emp_seq.ToString();
            //    ddlApprover_SelectedIndexChanged(null, null);
            //}
            //else
            //{
                LoadApprover();
            //}
        }

        protected void LoadApprover()
        {
            //var pos_seq = send.GetPosSeqFromEmpSeq(Session["EmpSeq"].ToString());
            ddlApprover.Enabled = true;
            DataTable dtb = send.GetCurrentApprover(Session["EmpSeq"].ToString(), null, "FIM_MONEY_REQUESTS", 1);

            if (dtb != null)
            {
                if (dtb.Rows.Count > 0)
                {
                    lblApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
                    SetEmpInfo(dtb.Rows[0]["emp_seq"].ToString(), dtb.Rows[0]["pos_seq"].ToString());
                    ddlApprover.Enabled = false;
                }
            }
        }

        protected void ddlApprover_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            SetEmpInfo(ddlApprover.SelectedValue);
        }

        protected void ddlApprover_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal)ddlApprover.Footer.FindControl("RadComboItemsCount")).Text = Convert.ToString(ddlApprover.Items.Count);
        }

        protected void ddlApprover_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlApprover.DataSource = emplist.ListEmployeeByType("('1', '2', '3')", null);
            ddlApprover.DataBind();
        }

        protected void ddlApprover_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((DataRowView)e.Item.DataItem)["full_name"].ToString();
            e.Item.Value = ((DataRowView)e.Item.DataItem)["sequence"].ToString();
        }

        protected void SetEmpInfo(string strEmpSeq, string strPosSeq = null)
        {
            if (strEmpSeq.Length > 0)
            {
                var model = emplist.GetInfo(strEmpSeq);

                lblEmpSeq.Text = model.emp_seq.ToString();//dtb.Rows[0]["sequence"].ToString();
                lblPosSeq.Text = strPosSeq ?? model.pos_seq.ToString();
                ddlApprover.Text = model.emp_name;//dtb.Rows[0]["full_name"].ToString();
                lblAppPosName.Text = model.pos_name + (string.IsNullOrEmpty(strPosSeq) ? (strPosSeq != model.pos_seq.ToString() ? " (รักษาการณ์แทน " + GetPositionName(strPosSeq) + ")" : "") : "");
                lblAppClassName.Text = model.class_name;//dtb.Rows[0]["class_name"].ToString();
                lblAppExecPosName.Text = model.exec_pos_name;//dtb.Rows[0]["exec_pos_name"].ToString();
                lblAppJobsiteName.Text = model.job_site_name;//dtb.Rows[0]["job_site_name"].ToString();
            }
        }

        protected string GetPositionName(string strPosSeq)
        {
            dbManager.Open();
            DataTable dtb = null;

            try
            {
                dbManager.CreateParameters(1);
                dbManager.AddParameters(0, "@pos_seq", strPosSeq);

                string strSQL = "SELECT pos_name FROM hrm_mp_positions where pos_seq = @pos_seq";

                dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];
                if (dtb.Rows.Count > 0)
                {
                    return dtb.Rows[0][0].ToString();
                }

                return "";
            }
            catch
            {
                return "";
            }
            finally
            {
                dbManager.Dispose();
            }
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            string strMoneyReqSeq = lblMoneyReqSeq.Text;
            M_FIM_MoneyRequests currentMoneyRequest;

            if (lblEmpSeq.Text.Length == 0)
            {
                ((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง");
                return;
            }
            if ((currentMoneyRequest = mr.GetInfo(strMoneyReqSeq)) == null)
            {
                ((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("ไม่พบข้อมูล ขอเบิก/ยืมเงินนี้");
                return;
            }

            try
            {
                M_MessageSend info = new M_MessageSend();
                info.send_date = DateTime.Today;
                info.ref_seq = main.ConvertNullInt(strMoneyReqSeq);
                info.ref_type = "fim_money_requests";
                info.ref_no = currentMoneyRequest.ref_no;
                info.send_text = "ส่งคำขอเบิก/ยืมเงิน : " + txtMoneyReqName.Text;
                info.from_emp_seq = main.ConvertNullInt(Session["EmpSeq"]);
                info.from_pos_seq = send.GetPosSeqFromEmpSeq("" + Session["EmpSeq"]);
                info.to_emp_seq = main.ConvertNullInt(lblEmpSeq.Text);
                info.to_pos_seq = main.ConvertNullInt(lblPosSeq.Text);
                info.from_send_seq = null;
                info.remarks = null;
                info.message_status = "0";
                info.approve_path_seq = main.ConvertNullInt(lblApprovePathSeq.Text);
                info.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                info.created_when = DateTime.Now;
                send.Insert(info);

                M_FIM_MoneyRequests info2 = new M_FIM_MoneyRequests();
                info2.money_req_seq = Convert.ToInt32(strMoneyReqSeq);
                info2.record_status = "P";
                info2.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                info2.updated_when = DateTime.Now;
                mr.ChangeStatus(info2);
                //((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("บันทึกเรียบร้อยแล้ว");

                PanelMessageSend.Visible = false;
                UpdateUI1("ViewAll");
            }
            catch (Exception ex)
            {
                throw ex;
                //((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("เกิดข้อผิดพลาดในการบันทึกข้อมูล");
            }
        }

        //protected void ddlBgmProject1_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    GetOptionProduct1();
        //    string strBgmProject1 =  ddlBgmProject1.SelectedValue;
        //    lblBgmProjOperCode.Text = oper.ProjectOprationCode(strBgmProject1);
        //}

        //protected void GetOptionProduct1()
        //{
        //    string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
        //    string strYear = txtBgmYear.Text;

        //    ddlBgmProject1.DataSource = ProjOper.GetList(strBgmSourceSeq, strYear, null, null, null, true, true);
        //    ddlBgmProject1.DataBind();
        //}
    }
}
